﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Supermodel.DomainModel;
using Supermodel.Exceptions;
using Supermodel.MVC.FormModels;
using Supermodel.UOW;

namespace Supermodel.Repository {
    public class SimpleSqlDataRepo<EntityT> : ISqlDataRepo<EntityT> where EntityT : Entity<EntityT>, new()
    {
		#region Properties
        virtual protected DbSet<EntityT> _set
        {
			get { return UnitOfWorkContextCore.CurrentUnitOfWork.Set<EntityT>(); }
		}
        virtual public IQueryable<EntityT> Items
        {
            get { return _set; }
        }
		#endregion

		#region Methods
        virtual public void Add(EntityT item)
        {
			if (item.Id == 0) _set.Add(item);
		}
		virtual public void Delete(EntityT item)
		{
		    _set.Remove(item);
		}
		virtual public EntityT GetById(long id) {
			var elements = Items.Where(p => p.Id == id);
			if (elements.Count() != 1) throw new SupermodelException("GetById count != 1");
			EntityT item = elements.First();
			return item;
		}
		virtual public IEnumerable<EntityT> GetAll() {
			return Items.ToList();
		}
        virtual public List<DropdownFormModel.Option> GetDropdownOptions()
        {
            var all = GetAll();
            if (all.Count() == 0) return new List<DropdownFormModel.Option>();
            return all.AsQueryable().OrderBy(p => p.Label).Select(item => new DropdownFormModel.Option(item.Id.ToString(), item.Label)).ToList();
        }
        virtual public List<ListBoxFormModel.Option> GetMultiSelectOptions()
        {
            var all = GetAll();
            if (all.Count() == 0) return new List<ListBoxFormModel.Option>();
            return all.AsQueryable().OrderBy(p => p.Label).Select(item => new ListBoxFormModel.Option(item.Id.ToString(), item.Label)).ToList();
        }
        #endregion	
	}
}
